const Comment = require('../models/comments')
const Answer = require('../models/answers')

class CommentController {
  // =================回答的(一级)评论列表=============
  async getCommentList(ctx) {
    // 分页逻辑
    let { perPage = 10, page = 1}  = ctx.query // 默认每页十条数据，从第一页起步
    // 防止输入负数
    perPage = Math.max(perPage * 1, 1) 
    page = Math.max(page * 1,1) 

    // 获取问题id和回答id
    const { questionId, answerId } = ctx.params
    // 评论列表，需要加上评论人的信息
    const commentList = await Comment.find({
      questionId, answerId,rootComment: {$ne: null}
    }).limit(perPage).skip((page-1) * perPage).populate('commentor replyTo childrenReply')  
    ctx.body = commentList
  }

  // =================评论是否存在==============
  async isCommentExist(ctx, next) {
    const comment = await Comment.findById(ctx.params.commentId)
    if (!comment) {
      ctx.throw(404, '评论不存在')
    }
    await next()
  }

  // ========查找特定的评论(用于展示评论详情)========
  async findCommentById(ctx) {
    const fields = ctx.query.fields || ''
    const selectFields = fields.split(';').filter(item=>item).map(item=> ' +'+item).join('')
    // 问题创建者填充user、话题topic的信息
    const comment = await Comment.findById(ctx.params.commentId).select(selectFields).populate('commentor childrenReply')
    ctx.body = comment
  }

  // =================发表评论==================
  async addComment(ctx) {
    ctx.verifyParams({
      content: {type: 'string', required: true},
      rootComment: {type: 'string', required: false},
      replyTo: {type: 'string', required: false}
    })

    const commentor = ctx.state.user.userId
    const {questionId, answerId} = ctx.params

    // 判断创建的是一级评论还是二级评论
    const { rootComment = '' } = ctx.query

    // 创建一级评论
    const comment = await Comment({
      ...ctx.request.body, 
      questionId, 
      answerId, 
      commentor,
      rootComment,
      replyTo: ctx.state.user.userId
    }).save()
    // 创建二级评论,找到根评论并添加到
    if (rootComment!=='') {
      const root = await Comment.findById(rootComment)
      root.childrenReply.push(comment._id)
      root.save() // 保存
    }
    // 对应回答的评论数 +1
    await Answer.findByIdAndUpdate(answerId, {$inc: {commentCount: 1}})

    ctx.body = comment
  }

  // =================删除评论==================
  async deleteQuestion(ctx) {
    // 问题的拥有者才能删除问题
    const commentor = ctx.state.user.userId

    // 只能删除评论者自己的评论
    if (commentor.toString() === ctx.state.user.userId) {
      await Comment.findByIdAndRemove(ctx.params.commentId)
      await Answer.findByIdAndUpdate(answerId, {$inc: {commentCount: -1}})
      ctx.status = 204
    } else {
      ctx.throw(403, '没有权限')
    }
  }
}

module.exports = new CommentController()